<template>
    <div style="border: 1px solid #ccc; margin-top: 10px">
        <Toolbar
            :defaultConfig="toolbarConfig"
            :editor="editorRef"
            style="border-bottom: 1px solid #ccc"
        />
        <Editor
            style="height: 400px; overflow-y: hidden; font-weight: normal"
            :defaultConfig="editorConfig"
            v-model.trim="content"
            @onCreated="handleCreated"
        />
    </div>
</template>

<script setup>
import { UpLoadUrl } from "@/config/index";
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, shallowRef, ref } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage } from "element-plus";

const editorRef = shallowRef();
const content = ref("");

const toolbarConfig = {
    toolbarKeys: [
        "bold",
        "italic",
        "underline",
        "through",
        "color",
        "bgColor",
        "clearStyle",
        "|",
        "bulletedList",
        "numberedList",
        "|",
        "insertLink",
        "uploadImage",
        "insertTable",
        "|",
        "undo",
        "redo"
    ]
};
const editorConfig = {
    MENU_CONF: {
        uploadImage: {
            server: UpLoadUrl, // 你的图片上传接口
            fieldName: "file", // 上传表单字段名
            withCredentials: true,
            customInsert(res, insertFn) {
                if (res.code == "1") {
                    insertFn(res.data.url);
                } else {
                    ElMessage.error(res.message);
                }
            }
        }
    }
};

onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor) => {
    editorRef.value = editor;
};

defineExpose({
    content,
    clear: () => {
        editorRef.value.clear();
    },
    setContent: (val) => {
        content.value = val;
    }
});
</script>
